package cmd

import (
	"app/config"
	"app/utils/helper"
	"context"
	"github.com/spf13/cobra"
	"log"
	"os"
	"os/signal"
	"sync"
	"syscall"
)

var (
	configYml string
)

func init() {
	//解析配置文件参数
	rootCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "etc/config.yaml", "")
}

// Execute : apply commands
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(-1)
	}
}

var rootCmd = &cobra.Command{
	Use:          "app",
	Short:        "start http",
	Example:      "app -c etc/config.yaml",
	SilenceUsage: true,
	PreRunE: func(cmd *cobra.Command, args []string) error {
		return config.LoadFromFile(configYml)
	},
	Run: func(cmd *cobra.Command, args []string) {
		var wg sync.WaitGroup
		for _, subCommand := range []*cobra.Command{queueCmd, cronCmd, httpCmd} {
			wg.Add(1)
			go func(subCommand *cobra.Command) {
				defer wg.Done()
				err := helper.Try(context.Background(), func(ctx context.Context) {
					subCommand.Run(subCommand, nil)
				})
				if err != nil {
					log.Printf("服务【%s】发生错误：%s", subCommand.Name(), err)
				}
			}(subCommand)
		}
		wg.Wait()
	},
	PostRunE: func(cmd *cobra.Command, args []string) error {
		return nil
	},
}

// waitForShutdown 等待关闭信号
func waitForShutdown() {
	closeSignal := make(chan os.Signal, 1)
	signal.Notify(closeSignal, syscall.SIGINT, syscall.SIGTERM)
	<-closeSignal
}
